package com.javaclimb.filmbuy.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javaclimb.filmbuy.common.Consts;
import com.javaclimb.filmbuy.dao.OrderGoodsRelDao;
import com.javaclimb.filmbuy.dao.OrderInfoDao;
import com.javaclimb.filmbuy.entity.*;
import com.javaclimb.filmbuy.exception.CustomException;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpCookie;
import java.util.*;

/*
* 订单信息service层
* */
@Service
public class OrderInfoService {

    @Resource
    private OrderInfoDao orderInfoDao;

    @Resource
    private AdminInfoService adminInfoService;

    @Resource
    private  UserInfoService userInfoService;

    @Resource
    private GoodsInfoService goodsInfoService;

    @Resource
    private OrderGoodsRelDao orderGoodsRelDao;

    /**
     * 增加一个订单信息
     */
    public OrderInfo add(OrderInfo orderInfo, GoodsInfo goodsInfo) {
        //总价格
        Integer total = orderInfo.getTotal();
        orderInfo.setTotalPrice(total * goodsInfo.getPrice() * goodsInfo.getDiscount());
        //订单状态
        orderInfo.setStatus("待付款");
        //订单id的组成：用户id+年月日时分+4位随机数
        String orderIdString = orderInfo.getUserId()+ DateUtil.format(new Date(), "yyyyMMddHHmm")+ RandomUtil.randomNumbers(4);
        orderInfo.setOrderId(Long.parseLong(orderIdString));
        //用户相关
        Account userInfo = getUserInfo(orderInfo.getUserId(), orderInfo.getLevel());
        orderInfo.setLinkAddress(userInfo.getAddress());
        orderInfo.setLinkMan(userInfo.getNickName());
        orderInfo.setLinkPhone(userInfo.getPhone());
        //订单时间
        orderInfo.setCreateTime(DateUtil.formatDateTime(new Date()));
        //生成订单
        orderInfoDao.insertSelective(orderInfo);

        //商品表更新
        goodsInfo.setSales(goodsInfo.getSales()+orderInfo.getTotal());
        goodsInfoService.update(goodsInfo);

        //建立关系
        OrderGoodsRel orderGoodsRel = new OrderGoodsRel();
        orderGoodsRel.setGoodsId(goodsInfo.getId());
        orderGoodsRel.setOrderId(orderInfo.getId());
        orderGoodsRel.setCount(orderInfo.getTotal());
        orderGoodsRelDao.insertSelective(orderGoodsRel);
        return orderInfo;
    }

    /*
     * 根据主键id删除一个订单信息
     * */
    @Transactional
    public void delete(Long id) {
        orderInfoDao.deleteByPrimaryKey(id);
        orderGoodsRelDao.deleteByOrderId(id);
    }

    /*
     * 更新一个管理员
     * */
    public void update(OrderInfo orderInfo) {
        orderInfoDao.updateByPrimaryKeySelective(orderInfo);
    }

    /*
     * 根据主键id查询一个管理员
     * */
    public OrderInfo findById(Long id) {
        return orderInfoDao.selectByPrimaryKey(id);
    }

    /**
     * 根据用户id和用户等级level查询用户对象
     */
    private Account getUserInfo(Long userId,Integer level) {
        Account account = new Account();
        if(level == 1){
            account = adminInfoService.findById(userId);
        }
        if(level == 2){
            account = userInfoService.findById(userId);
        }
        return account;
    }
    /*
     *分享查询订单信息
     */
    public PageInfo<OrderInfo>findPages(Long userId, Integer level, Integer PageNum, Integer pageSize, HttpServletRequest request){
     Account account=(Account) request.getSession().getAttribute(Consts.USER);
     if(account==null){
         throw new CustomException("1001","session已失效，请重新登录");
     }
     List<OrderInfo>orderInfos=new ArrayList<>();
     //管理员查询全部
        if(level==1){
            orderInfos=orderInfoDao.selectAll();
        }else {//普通用户查自己的订单
            orderInfos=orderInfoDao.findByUserIdAndLevel(userId,level);
        }
        for (OrderInfo orderInfo : orderInfos) {
            packOrder(orderInfo);
        }
     return PageInfo.of(orderInfos);
    }
    /**
     * 前端页面查询某用户的所有订单，支持翻页
     */
    public PageInfo<OrderInfo> findFrontPages(Long userId, Integer level, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderInfo> orderInfos;
        if (userId == null) {
            orderInfos = new ArrayList<>();
        } else {
            orderInfos = orderInfoDao.findByUserIdAndLevel(userId, level);
        }
        for (OrderInfo orderInfo : orderInfos) {
            packOrder(orderInfo);
        }
        return PageInfo.of(orderInfos);
    }

    /**
     * 包装订单的用户和商品信息
     */
    private void packOrder(OrderInfo orderInfo) {
        // 包装用户信息
        orderInfo.setUserInfo(getUserInfo(orderInfo.getUserId(), orderInfo.getLevel()));
        // 先查到关联表
        Long orderId = orderInfo.getId();
        List<OrderGoodsRel> rels = orderGoodsRelDao.findByOrderId(orderId);
        // 要放入订单的商品列表
        List<GoodsInfo> goodsList = new ArrayList<>();
        for (OrderGoodsRel rel : rels) {
            GoodsInfo goodsInfo = goodsInfoService.findById(rel.getGoodsId());
            if (goodsInfo != null) {
                goodsInfo.setNum(rel.getCount());
                goodsList.add(goodsInfo);
            }
        }
        orderInfo.setGoodsList(goodsList);
    }

    /**
     * 改变订单状态
     */
    public void changeStatus(Long id,String status){
        OrderInfo orderInfo=orderInfoDao.findById(id);
        Long userId= orderInfo.getUserId();
        Integer level=orderInfo.getLevel();
        if(level==1){
            AdminInfo user=adminInfoService.findById(userId);
           if(status.equals("待观看")){
               Double account=user.getAccount();
               Double totalPrice=orderInfo.getTotalPrice();
               if(account<totalPrice){
                   throw new CustomException("-1","账户余额不足");
               }
               user.setAccount(account-totalPrice);
               adminInfoService.update(user);
           }
           if(status.equals("已退款")){
               user.setAccount(user.getAccount()+orderInfo.getTotalPrice());
               adminInfoService.update(user);
           }
        }
        if(level==2){
            UserInfo user=userInfoService.findById(userId);
            if(status.equals("待观看")){
                Double account=user.getAccount();
                Double totalPrice=orderInfo.getTotalPrice();
                if(account<totalPrice){
                    throw new CustomException("-1","账户余额不足");
                }
                user.setAccount(account-totalPrice);
                userInfoService.update(user);
            }
            if(status.equals("已退款")){
                user.setAccount(user.getAccount()+orderInfo.getTotalPrice());
                userInfoService.update(user);
            }
        }
        orderInfoDao.changeStatus(id,status);
    }

    /**
     * 总销售额
     */
    public Double totalPrice() {
        return orderInfoDao.totalPrice();
    }

    /**
     * 总销量
     */
    public Integer totalShopping(){
        return orderGoodsRelDao.totalShopping();
    }

    /*
     * 分类总销售额
     * */
    public List<Map<String, Object>> getTypePrice(){
        return orderInfoDao.getTypePrice();
    }

    /*
     * 分类总销量
     * */
    public List<Map<String, Object>> getTypeCount(){
        return orderInfoDao.getTypeCount();
    }
}












